package com.qfedu.utils;

import com.qfedu.dao.StudentDao;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author wangyu
 * @Classname: MyBatisUtils
 * @Description: TEST
 * @date 2022-04-11 20:12
 */
public class MyBatisUtils {
    private static SqlSessionFactory factory;
    private static final ThreadLocal<SqlSession> local = new ThreadLocal<SqlSession>();

    static {
        try {
//        加载mybatis配置文件
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
//        会话工厂
            factory = builder.build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSessionFactory getFactory() {
        return factory;
    }

    public static SqlSession getSqlSession(boolean isAutoCommit) {
        SqlSession sqlSession = local.get();
        if (sqlSession == null) {
//            通过sqlSessionFactory 调用 openSession 方法获取 sqlSession对象时，可以
//            通过设置参数判定事务是否自动提交， 如果参数设置为 true ,表示自动提交factory.openSession(true);
//            不设置参数或者参数为false 表示手动提交  sqlSession.commit();
            sqlSession = factory.openSession(isAutoCommit);
            local.set(sqlSession);
        }
//        连接
        return sqlSession;
//           通过会话获取Dao对象
    }


    // 手动事务管理
    public static SqlSession getSqlSession() {
        return getSqlSession(false);
    }

    // 自动事务管理
    public static <T extends Object> T getMapper(Class<T> c) {
        SqlSession sqlSession = getSqlSession(true);
        return sqlSession.getMapper(c);
    }
}
